﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System;
using System.Text;

public class AddScoreMoudle : MonoBehaviour
{
    private TMP_Text currentScore, maxScore;
    private int _score;
    private int _maxScore {
        get
        {
            return PlayerPrefs.GetInt("MaxScore", 0);
        }
        set
        {
            PlayerPrefs.SetInt("MaxScore", value);
        }
    }

    private Animator addScoreAnim;

    public EventExtends.IntEvent AddScoreEvent = new EventExtends.IntEvent();

    private BgColorAnim bgColorAnim;

    private void Awake()
    {
        currentScore = GameObject.Find("Canvas/Score").GetComponent<TMP_Text>();
        maxScore = GameObject.Find("Canvas/BeoreMaxScore").GetComponent<TMP_Text>();

        addScoreAnim = GameObject.Find("Canvas/AddScoreAnim/AddScoreAnim").GetComponent<Animator>();
        bgColorAnim = GameObject.Find("Canvas/Bg").GetComponent<BgColorAnim>();
    }

    private void Start()
    {
        //监听事件
        AddScoreEvent.AddListener((addScore, pos) => {
            _score += addScore;
            if (_score > _maxScore) _maxScore = _score;
            addScoreAnim.SetTrigger("Trigger");

            StringBuilder _content = new StringBuilder();
            if (addScore > -1) _content.Append("+");
            _content.Append(addScore);

            pos.z = 0;
            addScoreAnim.transform.parent.GetComponent<RectTransform>().position = pos;
            addScoreAnim.GetComponent<TMP_Text>().text = _content.ToString();


            if(UnityEngine.Random.Range(.0f, .99f) > .9f) bgColorAnim.ChangeEvent.Invoke();
        });
    }



    public void ReScan() => _score = 0;



    private void Update()
    {
        currentScore.text = $"{_score}";
        maxScore.text = $"{_maxScore}";
    }
}
